export default {
    props: {
        schema: {
            type: Object,
            default: null,
        },
    },
    inject: {},
    computed: {
        data() {
            return (this.schema && this.schema.data) || {};
        },
        form() {
            return this.aegleForm && this.aegleForm.form;
        },
        model: {
            get() {
                const field = this.schema.name;
                if (field && this.form) {
                    if (this.form.hasOwnProperty(field)) {
                        return this.form[field];
                    }
                }

                return null;
            },
            set(value) {
                const field = this.schema.name;
                if (field && this.form) {
                    if (this.form.hasOwnProperty(field)) {
                        this.form[field] = value;
                    }
                }
            },
        },
        style() {
            return this.schema && this.schema.style || {};
        },
        
    },
    beforeCreate() {
        let parent = this.$options.parent;
        let aegleForm = null;

        while (parent) {
            if (parent.schema && parent.schema.tag == "aegle-form") {
                aegleForm = parent.schema.ref;
                break;
            } else {
                parent = parent.$options.parent;
            }
        }
        if (aegleForm) {
            this.$options.inject.aegleForm = { from: aegleForm };
        }
    },
    created() {
       this.$set( this.aegleForm.form,this.schema.name,null)
    },
    watch: {
        "schema.name": {
            handler(newName,oldName) {
                let value = this.aegleForm.form[oldName] || null
                this.$delete( this.aegleForm.form,oldName)
                this.$set( this.aegleForm.form,newName,value)
            }
        }
    }
}